package com.example.producer.client.order;

import com.example.common.entity.MsgTest;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @description: 异步顺序消息
 * @author TAO
 * @date 2021/8/30 23:21
 */
public class AsyncOrderProducer {

    public static void main(String[] args) throws Exception {
        DefaultMQProducer producer = new DefaultMQProducer("producer-group");

        producer.setNamesrvAddr("118.31.64.130:9876");
        //3.启动producer
        producer.start();

        //构建消息集合
        List<MsgTest> msgList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            msgList.add(new MsgTest(100, "我是id为100的第"+(i+1)+"条消息", new Date()));
        }

        //发送消息
        for (int i=0;i<msgList.size();i++){
            Message message = new Message("first-topic-str", "tag1", "i" + i, msgList.get(i).getContext().getBytes());
            producer.send(message, new MessageQueueSelector() {
                @Override
                public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
                    Integer orderId = (Integer) arg;
                    long index = orderId % mqs.size();
                    return mqs.get((int) index);
                }
            }, msgList.get(i).getId(), new SendCallback() {
                public void onSuccess(SendResult sendResult) {
                    System.out.println("发送结果：" + sendResult);
                }
                public void onException(Throwable e) {
                    System.out.println("发送异常：" + e);
                }
            });
        }

        Thread.sleep(5000);
        producer.shutdown();
    }

}
